import { createContext, PropsWithChildren, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from "react";
import SignIn from "../login/SignIn";
import { ErrorOutline as ErrorOutlineIcon } from "@mui/icons-material";
import * as request from "../utils/request";
import { ChildProcessWithoutNullStreams } from "child_process";
import useAsyncFn from "../utils/useAsyncFunc";

interface ContextValue{
    token:string;
}

const context = createContext<ContextValue>({token:""})

function saveToken(token:string){
    sessionStorage.setItem("token",token);
    request.useToken(token);
}

function useAutoLogout(token:string|null,logout:()=>any){
    useEffect(()=>{
        if(!token){
            return
        }
        const interval = setInterval(()=>{

        },1000)
        return ()=>{
            clearInterval(interval)
        }
    })    
}
interface UserProviderProps{}

async function fetchUser(){

}

export const UserProvider = ({children}:PropsWithChildren<UserProviderProps>)=>{
    const defaultToken = sessionStorage.getItem("token")
    const [token,_setToken] = useState(defaultToken)
    const [userResult, doFetchUser, setUser] = useAsyncFn(fetchUser, []);

    const setToken = useCallback((token:string)=>{
        _setToken(token);
        saveToken(token);
    },[])
    const logout = useCallback(async()=>{

    },[setToken])
    if(!token){
        return (<SignIn/>)
    }
    if (userResult.error) {
        return (
          <div className="fixed top-0 left-0 flex h-screen w-screen flex-col items-center justify-center text-6xl">
            <ErrorOutlineIcon fontSize="inherit" />
            <div className="mt-4 text-sm text-gray-500">{userResult.error.message || "Ooops, something went wrong"}</div>
          </div>
        );
      }
      if (userResult.loading || !userResult.value) {
        console.log("userResult.loading");
        //return <Loading />;
      }
      return (
        <context.Provider value={{ token }}>{children}</context.Provider>
      );
    //   return (
    //     // <context.Provider value={{ user: userResult.value, token, logout, refresh: refresh }}>
    //     //   {/* <WebSocketProvider token={token}>{children}</WebSocketProvider> */}
    //     // </context.Provider>
    //   );
}